package com.ds.admin.org.department.role;


import com.ds.admin.iorg.department.role.IRefDeparmentAPI;
import com.ds.admin.org.role.RolePopTree;
import com.ds.common.JDSException;
import com.ds.config.ListResultModel;
import com.ds.config.TreeListResultModel;
import com.ds.esb.config.EsbBeanAnnotation;
import com.ds.esd.client.ESDClient;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.util.TreePageUtil;
import com.ds.org.*;
import com.ds.server.OrgManagerFactory;

import java.util.ArrayList;
import java.util.List;

@EsbBeanAnnotation
public class RefDeparmentAPI implements IRefDeparmentAPI {


    public TreeListResultModel<List<RolePopTree>> loadChildOrg(String personId, OrgRoleType orgRoleType) {
        TreeListResultModel<List<RolePopTree>> resultModel = new TreeListResultModel<List<RolePopTree>>();
        List<Role> typeRoles = new ArrayList<>();
        if (orgRoleType != null) {
            List<Role> roles = OrgManagerFactory.getOrgManager().getAllRoles();
            if (roles.size() > 0) {
                for (Role role : roles) {
                    if (role.getType().getType().equals(orgRoleType.getType())) {
                        typeRoles.add(role);
                    }
                }
            }
        }
        resultModel = TreePageUtil.getDefaultTreeList(typeRoles, RolePopTree.class);
        return resultModel;
    }


    public ListResultModel<List<RefDeparmentRoleGrid>> getRefOrgRoles(String orgId, String roleType) {
        ListResultModel<List<RefDeparmentRoleGrid>> resultModel = new ListResultModel<List<RefDeparmentRoleGrid>>();
        List<RefDeparmentRoleGrid> roleViews = new ArrayList<>();
        try {
            Org org = this.getOrgManager().getOrgByID(orgId);
            List<Role> roles = org.getRoleList();
            for (Role role : roles) {
                RefDeparmentRoleGrid view = new RefDeparmentRoleGrid(org, role);
                roleViews.add(view);
            }
        } catch (JDSException e) {
            e.printStackTrace();

        } catch (OrgNotFoundException e) {
            e.printStackTrace();
        }
        resultModel.setData(roleViews);
        return resultModel;
    }


    public ESDClient getClient() throws JDSException {

        ESDClient client = ESDFacrory.getESDClient();

        return client;
    }

    OrgManager getOrgManager() throws JDSException {
        OrgManager orgManager = OrgManagerFactory.getOrgManager(this.getClient().getConfigCode());
        return orgManager;
    }
}
